package com.zhan.signalling.data.listener;

import java.util.Collection;
import java.util.Iterator;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.zhan.signalling.check.AccoutPermissionCheck;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.message.Message;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.util.RedisUtil;

/**
 * 踢出房间
 * @author knight
 *
 */
public class KickOutListener implements DataListener<Message> {

	public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
		
		// 校验权限
		AccoutPermissionCheck.check(client, SocketEvent.KICK_OUT_EVENT);
		String platform = client.getNamespace().getName();
		String groupId = client.get(Constants.GROUP_KEY);
		String token = data.getTo();
		Collection<SocketIOClient> allClient = client.getNamespace().getRoomOperations(groupId).getClients();
		Iterator<SocketIOClient> ite = allClient.iterator();
		JSONObject user = null;
		while(ite.hasNext()) {
			SocketIOClient cli = ite.next();
			user = client.get(Constants.USER_KEY);
			if(cli.get(Constants.USER_TOKEN).equals(token)) {
				cli.leaveRoom(groupId);
				cli.del(Constants.USER_KEY);
				cli.del(Constants.USER_TOKEN);
				cli.del(Constants.GROUP_KEY);
				cli.del(Constants.USER_TYPE);
				break;
			}
		}
		RedisUtil.addKickOut(platform + ":" +groupId, token);
		client.sendEvent(SocketEvent.KICK_OUT_EVENT, new Result("kick out group success", Constants.SUCCESS));
		client.getNamespace().getRoomOperations(groupId)
					.sendEvent(SocketEvent.EXIT_GROUP_EVENT, 
						new Result(user, Constants.SUCCESS));
	}

}
